package com.techstar.api.service.gis;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techstar.api.pojo.road.MainRoad;
import com.techstar.api.repos.gis.MainRoadRepos;
import com.techstar.api.service.ConfigProperties;
import com.techstar.api.service.GateWayApiProperties;
import com.techstar.api.service.HttpClientHeper;
import com.techstar.api.service.TrafficApiProperties;
import com.techstar.common.jackson.JacksonMapper;
import com.techstar.roma.http.GatewayService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author EinIce
 * @description 主干路
 * @date 2021年6月29日
 *
 */
@Slf4j
@Service
public class MainRoadService {
	
	@Autowired
	private MainRoadRepos beanRepos;
	
	private static final ObjectMapper objectMapper = JacksonMapper.instance.objectMapper;
	
	@Autowired
	private ConfigProperties configProperties; // 配置文件注入
	
	public void query(){
		GateWayApiProperties gateWayApiProperties = configProperties.romaApiProperties();
		TrafficApiProperties trafficApiProperties = configProperties.gismrApiProperties();
		if(gateWayApiProperties.testMode==true&&!"test".equals(trafficApiProperties.able)
				||"disable".equals(trafficApiProperties.able)) {
			log.info("DistrictCongestTrendService out");
			return;
		}
//		trafficApiProperties.param = String.format(trafficApiProperties.params,"" , DateTime.now().toString("yyyy-MM-dd hh:mm:ss"), "0");
		trafficApiProperties.param = "";
		HttpGet httpGet = new HttpGet();
		httpGet = (HttpGet) GatewayService.GateWay(httpGet,gateWayApiProperties, trafficApiProperties);
		CloseableHttpResponse response = null;
		String result = null;
        try {
            response = HttpClientHeper.instance.httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
            log.info(result);
            JsonNode jsonNode = objectMapper.readTree(result.toString()).get("data");
            if(jsonNode.size()<=0)return;
            
			List<MainRoad> list = objectMapper.readValue(jsonNode.toString(),new TypeReference<List<MainRoad>>() {});
			if(list.size()>0) beanRepos.deleteAll();
			beanRepos.saveAll(list);
            response.close();
        }catch (Exception e) {
        	e.printStackTrace();
		}
	}
}
